package com.ngmaster.socket.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ngmaster.apiserver.common.GainDeviceIdApiResponse;
import com.ngmaster.socket.ByteArray;
import com.ngmaster.socket.CmdType;
import com.ngmaster.socket.NetManager;
import com.ngmaster.socket.message.GainDeviceIdMessage;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 获取设备ID回调
 * */
public class CallbackGainDeviceId implements Callback {

    private static Logger logger = LoggerFactory.getLogger(CallbackGainDeviceId.class);

    @Override
    public void onFailure(Call call, IOException e) {
        logger.error("[req:" + call.request().body().toString() + "]", e);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String body = response.body().string();
        logger.info("[gain deviceId res] [reqLength:{}, reqMetaType:{}, callback:{}]", new Object[] {
                call.request().body().contentLength(), call.request().body().contentType(), body
        });

        JSONObject jsonObject = JSON.parseObject(body);
        GainDeviceIdApiResponse res = JSON.toJavaObject(jsonObject, GainDeviceIdApiResponse.class);
        if (res == null) {
            return;
        }
        if (res.getData() == null) {
            return;
        }
        GainDeviceIdMessage msg = new GainDeviceIdMessage();
        msg.setCmd(CmdType.GainDeviceId.getCmd());
        msg.setDeviceId(Integer.valueOf(res.getData().getId()));
        msg.setImei(res.getData().getIccid());
        msg.setByteArray(new ByteArray());
        msg.setDataLength(CmdType.GainDeviceId.getDataLength());
        msg.convertHexImeiToBytes();
        msg.serial();
        NetManager.getInstance().getTerminal(msg.getImei()).sendMessage(msg);
    }
}
